<template>
  <view class="water-monitor-layout">
    <!-- 左侧区域-区域树形结构 -->
    <view class="aside-panel" :class="{ collapsed: isAsideCollapsed }">
      <view class="aside-header">
        <view class="collapse-btn" @click="toggleAside">
          <uni-icons
            :type="isAsideCollapsed ? 'right' : 'left'"
            size="20"
            color="#409eff"
          ></uni-icons>
        </view>
        <uni-icons v-if="!isAsideCollapsed" type="location-filled" size="18" color="#409eff"></uni-icons>
        <text v-if="!isAsideCollapsed" class="header-title">区域每日流量</text>
      </view>
      
      <!-- 树形结构 -->
      <scroll-view v-if="!isAsideCollapsed" scroll-y class="tree-container" :show-scrollbar="true">
        <uni-load-more 
          v-if="treeLoading" 
          status="loading" 
          :content-text="{ contentdown: '加载中', contentrefresh: '加载中', contentnomore: '加载区域数据中...' }"
        ></uni-load-more>
        <view v-else>
          <view v-for="node in treeData" :key="node.id">
            <view 
              class="tree-node-item"
              :class="{ 'selected': selectedNode?.id === node.id }"
              @click="handleNodeClick(node)"
            >
              <view class="node-content">
                <uni-icons type="location" size="16" color="#409eff"></uni-icons>
                <text class="node-label">{{ node.label }}</text>
              </view>
              <!-- 递归渲染子节点 -->
              <view v-if="node.children && node.children.length > 0" class="node-children">
                <view 
                  v-for="child in node.children" 
                  :key="child.id"
                  class="tree-node-item child-node"
                  :class="{ 'selected': selectedNode?.id === child.id }"
                  @click.stop="handleNodeClick(child)"
                >
                  <view class="node-content">
                    <uni-icons type="location" size="14" color="#67c23a"></uni-icons>
                    <text class="node-label">{{ child.label }}</text>
                  </view>
                  <!-- 可以继续递归更深层级 -->
                  <view v-if="child.children && child.children.length > 0" class="node-children">
                    <view 
                      v-for="grandchild in child.children" 
                      :key="grandchild.id"
                      class="tree-node-item grandchild-node"
                      :class="{ 'selected': selectedNode?.id === grandchild.id }"
                      @click.stop="handleNodeClick(grandchild)"
                    >
                      <view class="node-content">
                        <uni-icons type="location" size="12" color="#909399"></uni-icons>
                        <text class="node-label">{{ grandchild.label }}</text>
                      </view>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 右侧主内容区 -->
    <view class="main-content">
      <!-- 时间筛选栏 -->
      <view class="time-filter-bar">
        <!-- 时间选择 -->
        <view class="date-picker-group">
          <uni-datetime-picker 
            v-model="dateRange" 
            type="daterange"
            rangeSeparator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="handleDateChange"
            :clear-icon="false"
          />
        </view>
        
        <!-- 快捷时间按钮 -->
        <view class="quick-time-group">
          <button class="quick-btn" size="mini" type="primary" @click="setQuickTime('today')">今日</button>
          <button class="quick-btn" size="mini" type="primary" @click="setQuickTime('yesterday')">昨天</button>
          <button class="quick-btn" size="mini" type="primary" @click="setQuickTime('week')">本周</button>
          <button class="quick-btn" size="mini" type="primary" @click="setQuickTime('month')">当月</button>
          <button class="quick-btn" size="mini" type="primary" @click="setQuickTime('lastMonth')">上月</button>
        </view>
        
        <!-- 基准线控制 -->
        <view class="baseline-control">
          <switch 
            :checked="showWaterValueLine" 
            @change="handleBaselineToggle"
            color="#409eff"
          />
          <text class="baseline-text">显示基准线</text>
          <text class="baseline-tip" v-if="!waterValue">(当前区域无基准流量)</text>
        </view>
      </view>

      <!-- 标签页切换 -->
      <uni-segmented-control 
        :current="activeTab" 
        :values="['折线图', '表格']" 
        @clickItem="onTabChange"
        styleType="button"
        activeColor="#409eff"
        class="tab-control"
      />

      <!-- 数据展示区域 -->
      <view class="data-container">
        <!-- 图表展示 -->
        <view class="chart-container" v-if="activeTab === 0">
          <uni-load-more 
            v-if="chartLoading" 
            status="loading" 
            :content-text="{ contentdown: '加载中', contentrefresh: '加载中', contentnomore: '加载区域每日流量数据中...' }"
          ></uni-load-more>
          <view v-else-if="!isChartEmpty" class="chart-wrapper">
            <qiun-data-charts
              :key="chartKey"
              type="line"
              :opts="chartOpts"
              :chartData="chartData"
              canvasId="areaDailyFlow"
            />
          </view>

          <view v-else class="empty-tip">
            <uni-icons type="info-filled" size="32" color="#909399"></uni-icons>
            <text class="empty-text">请选择区域并设置日期范围查询每日数据</text>
          </view>
        </view>

        <!-- 表格展示 -->
        <scroll-view scroll-y class="table-container" v-if="activeTab === 1">
          <uni-load-more 
            v-if="tableLoading" 
            status="loading" 
            :content-text="{ contentdown: '加载中', contentrefresh: '加载中', contentnomore: '加载每日数据中...' }"
          ></uni-load-more>
          <view v-else-if="tableData.length > 0" class="table-wrapper">
            <view class="table-row table-header">
              <text class="table-cell">日期</text>
              <text class="table-cell">当日流量(吨)</text>
            </view>
            <view class="table-row" v-for="(item, index) in tableData" :key="index">
              <text class="table-cell">{{ formatDateTime(item.analyseDate) }}</text>
              <text class="table-cell">{{ item.todayWaterVal }}</text>
            </view>
          </view>
          <view v-else class="empty-tip">
            <uni-icons type="info-filled" size="32" color="#909399"></uni-icons>
            <text class="empty-text">当前日期范围内无区域每日流量数据</text>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script setup>
import qiunDataCharts from '@/uni_modules/qiun-data-charts/components/qiun-data-charts/qiun-data-charts.vue'
import { watch } from 'vue'
import { ref, computed, onMounted } from 'vue'
import dayjs from 'dayjs'
// 引入API方法
import { listArea } from '@/api/water/area'
import { listAreaAnalyse } from '@/api/water/areaAnalyse'


// ======================== 响应式数据 ========================
const currentPage = ref(1)
const pageSize = ref(50)
const totalData = ref([])

const treeData = ref([])
const selectedNode = ref(null)
const dateRange = ref([])

const treeLoading = ref(false)
const chartLoading = ref(false)
const tableLoading = ref(false)

const activeTab = ref(0) // 0: 图表, 1: 表格
const tableData = ref([])

// 基准线相关
const showWaterValueLine = ref(true)
const waterValue = ref(null)

// 图表配置 (使用 uCharts)
const chartData = ref({})
const chartKey = ref(0)
const chartOpts = ref({
  color: ['#409EFF', '#f56c6c'],
  padding: [15, 15, 0, 5],
  enableScroll: false,
  legend: {
    show: true,
    position: 'top',
    float: 'right',
    padding: 5,
    margin: 5,
    fontSize: 12
  },
  xAxis: {
    disableGrid: true,
    scrollShow: false,
    itemCount: 0,
    rotateLabel: true,
    labelAngle: 45
  },
  yAxis: {
    gridType: 'dash',
    dashLength: 2,
    data: [{
      min: 0,
      title: '当日流量(吨)'
    }]
  },
  extra: {
    line: {
      type: 'curve',
      width: 2,
      activeType: 'hollow'
    }
  }
})


const isChartEmpty = computed(() => {
  return !chartData.value.series || chartData.value.series.length === 0
})

const isAsideCollapsed = ref(false)
const toggleAside = () => {
  isAsideCollapsed.value = !isAsideCollapsed.value
  // 延迟强制图表重新渲染,等待动画完成
  setTimeout(() => {
    chartKey.value++
  }, 350)
}

// ======================== 页面初始化 ========================
onMounted(() => {
  initAreaTree()
  setQuickTime('month')
})

// ======================== 树形结构逻辑 ========================
const initAreaTree = async () => {
  treeLoading.value = true
  try {
    const areaRes = await listArea({ pageNum: 1, pageSize: 1000 })
    if (areaRes.code !== 200) throw new Error('获取区域数据失败')
    
    const areaTree = buildAreaTree(areaRes.rows)
    treeData.value = areaTree
  } catch (err) {
    uni.showToast({
      title: err.message || '初始化数据失败',
      icon: 'none'
    })
  } finally {
    treeLoading.value = false
  }
}

const buildAreaTree = (areas) => {
  const areaMap = new Map()
  const rootAreas = []

  areas.forEach(area => {
    areaMap.set(area.id, {
      ...area,
      type: 'area',
      label: area.areaName,
      children: []
    })
  })

  areaMap.forEach(area => {
    const parentId = area.parentAreaId
    if (!parentId || parentId === 0 || !areaMap.has(parentId)) {
      rootAreas.push(area)
    } else {
      const parentArea = areaMap.get(parentId)
      parentArea.children.push(area)
    }
  })

  return rootAreas
}

const handleNodeClick = (node) => {
  console.log('节点被点击:', node)
  if (node.type === 'area') {
    selectedNode.value = node
    // 从选中的区域节点中获取基准值
    waterValue.value = node.waterValue !== undefined && node.waterValue !== null
      ? Number(node.waterValue)
      : null
    
    console.log('选中区域:', {
      id: node.id,
      名称: node.label,
      基准值: waterValue.value,
      时间范围: dateRange.value
    })
    
    fetchAreaDailyData()
  }
}

const handleNodeSelect = (node) => {
  handleNodeClick(node)
}

// ======================== 时间筛选逻辑 ========================
const setQuickTime = (type) => {
  let startTime = ''
  let endTime = ''

  switch (type) {
    case 'today':
      startTime = dayjs().format('YYYY-MM-DD')
      endTime = dayjs().format('YYYY-MM-DD')
      break
    case 'yesterday':
      startTime = dayjs().subtract(1, 'day').format('YYYY-MM-DD')
      endTime = dayjs().subtract(1, 'day').format('YYYY-MM-DD')
      break
    case 'week':
      startTime = dayjs().startOf('week').add(1, 'day').format('YYYY-MM-DD')
      endTime = dayjs().endOf('week').add(1, 'day').format('YYYY-MM-DD')
      break
    case 'month':
      startTime = dayjs().startOf('month').format('YYYY-MM-DD')
      endTime = dayjs().endOf('month').format('YYYY-MM-DD')
      break
    case 'lastMonth':
      startTime = dayjs().subtract(1, 'month').startOf('month').format('YYYY-MM-DD')
      endTime = dayjs().subtract(1, 'month').endOf('month').format('YYYY-MM-DD')
      break
  }

  dateRange.value = [startTime, endTime]
  if (selectedNode.value) fetchAreaDailyData()
}

const handleDateChange = () => {
  if (selectedNode.value) fetchAreaDailyData()
}

const onTabChange = (e) => {
  activeTab.value = e.currentIndex
}

const handleBaselineToggle = (e) => {
  showWaterValueLine.value = e.detail.value
}

// ======================== 数据查询逻辑 ========================
const fetchAreaDailyData = async () => {
  if (!selectedNode.value || !dateRange.value[0] || !dateRange.value[1]) {
    uni.showToast({
      title: '请先选择区域并设置日期范围',
      icon: 'none'
    })
    return
  }

  chartLoading.value = true
  tableLoading.value = true
  currentPage.value = 1
  totalData.value = []
  const pageSizeVal = pageSize.value
  let hasMoreData = true

  try {
    while (hasMoreData) {
      const params = {
        areaId: selectedNode.value.id,
        startTime: dateRange.value[0],
        endTime: dateRange.value[1],
        pageNum: currentPage.value,
        pageSize: pageSizeVal
      }

      const res = await listAreaAnalyse(params)
      if (res.code !== 200 || !Array.isArray(res.rows)) {
        throw new Error(`第${currentPage.value}页区域流量数据请求失败`)
      }

      const currentPageData = res.rows
      totalData.value.push(...currentPageData)

      hasMoreData = currentPageData.length === pageSizeVal
      currentPage.value++
    }

    const sortedData = totalData.value.sort((a, b) => {
      return new Date(a.analyseDate) - new Date(b.analyseDate)
    })

    // 更新图表数据
    updateChartData(sortedData)

    tableData.value = sortedData
    
    console.log('数据加载完成:', {
      区域ID: selectedNode.value.id,
      区域名称: selectedNode.value.label,
      数据条数: sortedData.length,
      基准值: waterValue.value
    })

    if (sortedData.length === 0) {
      uni.showToast({
        title: '当前日期范围内无区域每日流量数据',
        icon: 'none'
      })
    }

  } catch (err) {
    uni.showToast({
      title: err.message || '区域每日流量数据查询失败',
      icon: 'none'
    })
  } finally {
    chartLoading.value = false
    tableLoading.value = false
  }
}

const updateChartData = (sortedData) => {
  const categories = sortedData.map(item => dayjs(item.analyseDate).format('MM-DD'))
  const seriesData = sortedData.map(item => Number(item.todayWaterVal) || 0)
  
  const series = [{
    name: '区域每日流量',
    data: seriesData
  }]

  // 如果显示基准线且有基准值
  if (showWaterValueLine.value && waterValue.value !== null && waterValue.value >= 0) {
    const baselineData = new Array(sortedData.length).fill(Number(waterValue.value))
    series.push({
      name: `基准流量线:${waterValue.value.toFixed(2)}吨`,
      data: baselineData,
      lineType: 'dash'
    })
    
    // 动态调整y轴最大值
    const validData = seriesData.filter(val => val !== null && !isNaN(val))
    const dataMax = validData.length > 0 ? Math.max(...validData) : 0
    const offset = Math.max(dataMax, waterValue.value) * 0.1 || 1
    chartOpts.value.yAxis.data[0].max = Math.max(dataMax, waterValue.value) + offset
  } else {
    chartOpts.value.yAxis.data[0].max = null
  }

  // 强制更新图表数据
  chartData.value = {
    categories: categories,
    series: series
  }
  
  // 输出调试信息
  console.log('图表数据更新:', {
    categories: categories.length,
    seriesData: seriesData.length,
    chartData: chartData.value
  })
}

const formatDateTime = (date) => {
  return dayjs(date).format('YYYY-MM-DD')
}

// 监听图表数据变化
watch(chartData, (newData) => {
  if (!newData || !newData.categories) {
    return
  }
  
  const len = newData.categories.length || 0
  const itemCount = len > 15 ? 15 : len

  // 更新图表配置
  chartOpts.value = {
    ...chartOpts.value,
    xAxis: {
      ...chartOpts.value.xAxis,
      itemCount: itemCount,
      scrollShow: false,
    }
  }

  console.log('图表配置更新:', { len, itemCount, chartOpts: chartOpts.value })
  
  // 延迟触发重新渲染
  setTimeout(() => {
    chartKey.value++
  }, 100)
}, { deep: true, immediate: false })

// 监听基准线开关变化
watch([showWaterValueLine, waterValue], () => {
  if (tableData.value.length > 0) {
    console.log('基准线状态变化，重新渲染图表')
    updateChartData(tableData.value)
  }
}, { deep: true })
</script>

<style scoped>
.water-monitor-layout {
  display: flex;
  height: 100vh;
  background-color: #f5f5f5;
}

.aside-panel {
  width: 280px;
  background-color: #ffffff;
  border-right: 1px solid #e9ecef;
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  transition: width 0.3s ease;
}

.aside-panel.collapsed {
  width: 40px;
}

.aside-header {
  display: flex;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #e9ecef;
}

.collapse-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  margin-right: 8px;
}

.header-title {
  margin-left: 8px;
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.tree-container {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.tree-node-item {
  margin-bottom: 8px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.tree-node-item.selected > .node-content {
  background-color: #ecf5ff;
  border-left: 3px solid #409eff;
}

.node-content {
  display: flex;
  align-items: center;
  padding: 10px;
  border-radius: 4px;
  cursor: pointer;
}

.node-content:hover {
  background-color: #f5f7fa;
}

.node-label {
  margin-left: 8px;
  font-size: 14px;
  color: #333;
}

.node-children {
  margin-left: 20px;
  margin-top: 4px;
}

.child-node {
  margin-bottom: 6px;
}

.child-node .node-label {
  font-size: 13px;
}

.grandchild-node {
  margin-bottom: 4px;
}

.grandchild-node .node-label {
  font-size: 12px;
  color: #606266;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 15px;
  background-color: #ffffff;
  overflow: hidden;
}

.time-filter-bar {
  margin-bottom: 15px;
}

.date-picker-group {
  margin-bottom: 10px;
}

.quick-time-group {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 10px;
}

.quick-btn {
  flex-shrink: 0;
}

.baseline-control {
  display: flex;
  align-items: center;
  gap: 8px;
}

.baseline-text {
  font-size: 14px;
  color: #333;
}

.baseline-tip {
  font-size: 12px;
  color: #909399;
}

.tab-control {
  margin-bottom: 15px;
}

.data-container {
  flex: 1;
  overflow: hidden;
}

.chart-container,
.table-container {
  height: 100%;
}

.chart-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.table-wrapper {
  width: 100%;
}

.table-row {
  display: flex;
  border-bottom: 1px solid #ebeef5;
}

.table-header {
  background-color: #f5f7fa;
  font-weight: bold;
}

.table-cell {
  flex: 1;
  padding: 12px;
  text-align: center;
  font-size: 14px;
  border-right: 1px solid #ebeef5;
}

.table-cell:last-child {
  border-right: none;
}

.empty-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
}

.empty-text {
  margin-top: 10px;
  font-size: 14px;
}
</style>